<template>
    <div class="justify-center flex">
        <el-form ref="formRef" v-loading="loading" :model="formData" :rules="formRules" label-suffix=":"
                 label-width="80px" style="width: 500px">
            <div class="flex justify-start">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="formData.username" placeholder="用户名"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="formData.nickname" placeholder="昵称"></el-input>
                </el-form-item>
            </div>
            <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="formData.gender">
                    <el-radio :value="2" label="未知"/>
                    <el-radio :value="0" label="男"/>
                    <el-radio :value="1" label="女"/>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="formData.phone" placeholder="联系号码" style="width: 440px"/>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="formData.email" placeholder="邮箱地址" style="width: 440px"/>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-switch v-model="formData.status"
                           :active-color="'#fff'"
                           :active-text="'启用'"
                           :active-value="1"
                           :inactive-color="'#000'"
                           :inactive-text="'停用'"
                           :inactive-value="0"
                           inline-prompt
                >
                </el-switch>
            </el-form-item>
            <el-form-item label="角色" prop="roleCodes">
                <el-select v-model="formData.roleCodes" clearable multiple style="width: 440px"
                           @change="handleRoleChange">
                    <el-option v-for="role in sysRoleList" :label="role.roleName" :value="role.roleCode">
                        {{ role.roleName }}
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <template #default="{row}">
                    <el-text type="danger">* 注：用户名添加后不允许修改</el-text>
                </template>
            </el-form-item>
            <el-form-item>
                <template #default="{row}">
                    <el-button type="primary" @click="submit">保存</el-button>
                    <el-button plain type="info" @click="cancel">取消</el-button>
                </template>
            </el-form-item>
        </el-form>

    </div>
</template>

<script setup>
import {ref, unref, reactive, onMounted} from "vue";
import instance from "@/api/request.js";
import useSysRole from "@/composables/useSysRole.js";
import {ElMessage} from "element-plus";

const emit = defineEmits(["submit", "cancel"])

const props = defineProps(["data"])

const formRef = ref()
const formData = reactive({
    username: '',
    nickname: '',
    gender: 2,
    status: 0,
    email: '',
    phone: '',
    roles: [],
    roleCodes: [],
})
const formRules = reactive({
    // 用户名：虽然 disabled，但如果后端需要校验可保留 required
    username: [
        {required: true, message: '用户名不能为空', trigger: 'blur'}
    ],
    // 昵称：必填，长度限制
    nickname: [
        {required: true, message: '请输入昵称', trigger: 'blur'},
        {min: 2, max: 20, message: '昵称长度在 2 到 20 个字符之间', trigger: 'blur'}
    ],
    // 性别：必选（单选）
    gender: [
        {required: true, message: '请选择性别', trigger: 'change'}
    ],
    // 手机号：必填，格式校验
    phone: [
        {required: true, message: '请输入手机号', trigger: 'blur'},
        {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号格式',
            trigger: 'blur'
        }
    ],
    // 邮箱：必填，格式校验
    email: [
        {required: false, message: '请输入邮箱地址', trigger: 'blur'},
        {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: 'blur'
        }
    ],
    // 状态：一般不需要校验，但如果你强制要求选择可以加上
    status: [
        {required: true, message: '请设置状态', trigger: 'change'}
    ],
    // 角色：至少选择一个角色
    roleCodes: [
        {
            required: true,
            message: '请至少选择一个角色',
            trigger: 'change',
            type: 'array'
        }
    ]
})

function submit() {
    formRef.value.validate(valid => {
        if (!valid) {
            ElMessage.error('请检查表单');
            return;
        }
        instance.post("/system/user/save_user", {
            ...unref(formData)
        }).then(res => {
            if (res.code === 200) {
                ElMessage.success(res.message)
                emit('submit', formData)
            }else {
                ElMessage.error(res.data || res.message)
            }
        });
    });

}

function cancel() {
    // formRef.value.resetFields()
    emit('cancel')
}

const loading = ref(false)

async function findOne(username) {
    loading.value = true;
    await instance.post(`/system/user/${username}`).then(res => {
        Object.assign(formData, res.data)
        formData.roleCodes = formData.roles.map(role => role.roleCode);
        loading.value = false;
    })
    return null;
}

let sysRole = useSysRole();
sysRole.loadData()
let sysRoleList = sysRole.roleList;


onMounted(async () => {
    // await findOne(props.data.username);
});

const handleRoleChange = (array) => {
    formData.roleCodes = array;
}
</script>

<style scoped>

</style>